package cn.basic.auth.service.impl;

import cn.basic.auth.domain.Menu;
import cn.basic.auth.mapper.MenuMapper;
import cn.basic.auth.service.IMenuService;
import cn.basic.auth.vo.query.MenuQuery;
import cn.basic.auth.vo.result.MenuVo;
import cn.basic.common.service.impl.IBaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
 * @description:
 * Menu--Service层实现类
 * @date: 2023/3/7 17:28
 * @author: ZhaoLc
 * @version: 1.0
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class IMenuServiceImpl extends IBaseServiceImpl<Menu,MenuQuery,MenuVo> implements IMenuService {

    @Resource
    MenuMapper menuMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer update(Menu menu) {
        if(StringUtils.isEmpty(menu.getParent_id())) {
            menu.setParent_id(0L);
        }
        return menuMapper.update(menu);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer add(Menu menu) {
        if(StringUtils.isEmpty(menu.getParent_id())) {
            menu.setParent_id(0L);
        }
        return menuMapper.insert(menu);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteById(Serializable id) {
        try {
            // 删除菜单
            menuMapper.removeById(id);
            // 删除子菜单
            menuMapper.removeChildren(id);
        } catch (Exception e){
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteBatch(List<Long> ids) {
        try {
            // 删除菜单
            menuMapper.deleteBatch(ids);
            // 删除下面的子菜单
            menuMapper.removeChildrenBatch(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public List<MenuVo> getParent() {
        return menuMapper.loadParent();
    }

    @Override
    public List<Long> getMenusById(Serializable id) {
        return menuMapper.loadMenusById(id);
    }

    @Override
    public List<MenuVo> getTreeById(Serializable id) {
        return menuMapper.loadTreeById(id);
    }
}
